package com.yueqian.framework.exception;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.yueqian.framework.enmus.ExceptionEnum;
import com.yueqian.framework.entity.ResultEntity;

import cn.hutool.core.util.ObjectUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpStatus.OK.value());
		ServletOutputStream outputStream = response.getOutputStream();
		if (ObjectUtil.equals(request.getAttribute("code"), ExceptionEnum.LOGIN_USER_IS_EXPIRE.getCode())) {
			outputStream.write(JSON.toJSONString(ResultEntity.error((Integer) request.getAttribute("code"), request.getAttribute("message").toString())).getBytes(StandardCharsets.UTF_8));
		} else {
			outputStream.write(JSON.toJSONString(ResultEntity.error(ExceptionEnum.USER_AUTH_FAIL.getCode(), ExceptionEnum.USER_AUTH_FAIL.getMessage())).getBytes(StandardCharsets.UTF_8));
		}
		outputStream.flush();
		outputStream.close();
	}
}
